﻿/* $RCSFile: HeaderMenuButton.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/WebControls/HeaderMenuButton.cs $
 * $log$
 * Revision 19 2011/02/22 01:23:08  christian.surieux
 *   V4 Migration 22/2/11
 * Revision 19 2011/02/22 01:22:16  christian.surieux
 *   V4 Migration 22/2/11
 * Revision 6 2010/08/06 19:56:30  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;

using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Core;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Helpers;
using AddonNice.Security;
using AddonNice.Configuration;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.UI.WebControls
{

	public class DivCtl : WebControl
	{
		protected override HtmlTextWriterTag TagKey
		{
			get
			{
				return HtmlTextWriterTag.Div;
			}
		}
	}

	/// <summary>
	/// Get the Logo from settings and display it
	/// </summary>
	/// 
	public class HeaderMenuButton : CompositeControl , IPortalMenu
	{
		Image Img			            =	new Image();
		DivCtl SlidingDiv               =   new DivCtl();
		RadPanelMenuNavigation mnu      =   new RadPanelMenuNavigation();

	
		private Style _ImageStyle;
		/// <summary>
		/// The style to be applied to Image.
		/// </summary>
		[
		Category("Style"),
		Description("The style to be applied to Image button"),
		DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
		PersistenceMode(PersistenceMode.InnerProperty)
		]
		public Style ImageStyle
		{
			get 
			{
				if (_ImageStyle == null) 
				{
					_ImageStyle = new Style();
					if (IsTrackingViewState)
						((IStateManager)_ImageStyle).TrackViewState();
				}
				return _ImageStyle;
			}
		}
		

		private Style _SlidingDivStyle;
		/// <summary>
		/// The style to be applied to SlidingDiv.
		/// </summary>
		[
		Category("Style"),
		Description("The style to be applied to Sliding Div containing RadPanelMenuNavigation"),
		DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
		PersistenceMode(PersistenceMode.InnerProperty)
		]
		public Style SlidingDivStyle
		{
			get 
			{
				if (_SlidingDivStyle == null) 
				{
					_SlidingDivStyle = new Style();
					if (IsTrackingViewState)
						((IStateManager)_SlidingDivStyle).TrackViewState();
				}
				return _SlidingDivStyle;
			}
		}
		

		private Style _PanelBarStyle;
		/// <summary>
		/// The style to be applied to PanelBar
		/// </summary>
		[
		Category("Style"),
		Description("The style to be applied to RadPanelMenuNavigation"),
		DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
		PersistenceMode(PersistenceMode.InnerProperty)
		]
		public Style PanelBarStyle
		{
			get 
			{
				if (_PanelBarStyle == null) 
				{
					_PanelBarStyle = new Style();
					if (IsTrackingViewState)
						((IStateManager)_PanelBarStyle).TrackViewState();
				}
				return _PanelBarStyle;
			}
		}
		

		


		bool _AutoHide = true;
		/// <summary> 
		/// Indicates if control should automatically hide after user move out and some timeout
		/// </summary> 
		[ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] 
		public bool AutoHide 
		{ 
			get{return _AutoHide;} 
			set{_AutoHide = value;} 
		} 

		// timeout value in (?)
		int _HideTimeOut  =   3000;
		[Category("Data"), PersistenceMode(PersistenceMode.Attribute)] 
		public int HideTimeOut
		{
			get
			{
				return _HideTimeOut;
			}
			set
			{
				_HideTimeOut = value;
			}
		}

		private bool _dataBindOnInit	=   true;
		/// <summary>
		/// Should bind in OnInit
		/// </summary>
		[DefaultValue(true)]
		public bool DataBindOnInit
		{
			get
			{
				return _dataBindOnInit;
			}
			set
			{
				_dataBindOnInit = value;
			}
		}

		protected override HtmlTextWriterTag TagKey
		{
			get
			{
				if (CoreTraceSwitch.Sw.TraceVerbose)
					Trace2.WriteLine( "[V]HeaderMenuButton TagKey GET.",CoreTraceSwitch.Sw.Info);
				return HtmlTextWriterTag.Div;
			}
		}

		#region IPortalMenu implementation
		
		public void ResetCache()
		{
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine("[V]HeaderMenuButton ResetCache BEG.",NavTraceSwitch.Sw.Info);
			mnu.ResetCache();
		}

		public void Rebind()
		{
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( "[V]HeaderMenuButton Rebind BEG.",NavTraceSwitch.Sw.Info);
			mnu.Rebind();
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( "[V]HeaderMenuButton Rebind END.", NavTraceSwitch.Sw.Info);
		}
	   
		public bool SelectMenuItem(int wPageId)
		{
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenuButton SelectMenuItem BEG PageId: {0}.", wPageId),NavTraceSwitch.Sw.Info);
			bool found  =   mnu.SelectMenuItem(wPageId);
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenuButton SelectMenuItem END found: {0}.", found),NavTraceSwitch.Sw.Info);
			return found;
		}

		public Control AjaxControl
		{
			get
			{
				return this;
			}
		}

		public bool ShouldRegisterInAjaxManager
		{
			get
			{
				return true;
			}
		}

		#endregion IPortalMenu

		public HeaderMenuButton()
		{
			EnableViewState     =   false;
            mnu.EnableViewState =   false;
            ClientIDMode        =   System.Web.UI.ClientIDMode.Static;
		}

		protected override void OnInit(EventArgs e)
		{
			if (CoreTraceSwitch.Sw.TraceVerbose)
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenuButton OnInit BEG DataBindOnInit: {0}, PortalSettings.IsUnderCRM: {1}.",
					DataBindOnInit,PortalSettings.IsUnderCRM),CoreTraceSwitch.Sw.Info);
			if( DataBindOnInit )
			{
				EnsureChildControls();
			}
			base.OnInit(e);
			//Registers in portal
			if ( !DesignMode )
			{
				PortalSettings portalSettings =     (PortalSettings)HttpContext.Current.Items[StStr.strPortalSettings];
				portalSettings.AddPortalMenu(this);
			}
			if (CoreTraceSwitch.Sw.TraceVerbose)
				Trace2.WriteLine( "[V]HeaderMenuButton OnInit END.",CoreTraceSwitch.Sw.Info);
		}

		/// <summary>
		/// This member overrides Control.CreateChildControls
		/// </summary>
		protected override void CreateChildControls()
		{
			if ( WebControlsTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenuButton CreateChildControls BEG ChildControlsCreated: {0}", ChildControlsCreated),WebControlsTraceSwitch.Sw.Info);
			CreateControlHierarchy();
			if ( WebControlsTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenuButton CreateChildControls END ChildControlsCreated: {0}", ChildControlsCreated),WebControlsTraceSwitch.Sw.Info);
		}


		void CreateControlHierarchy()
		{
			if ( WebControlsTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenuButton CreateControlHierarchy BEG ChildControlsCreated: {0}", ChildControlsCreated),WebControlsTraceSwitch.Sw.Info);

			ClearChildViewState();
			Controls.Clear();
			Img.SkinID                  =   "FloatButton";
			Img.ID                      =   "tbimage";
			Img.AlternateText           =   "Menu";
			Controls.Add(Img);
			SlidingDiv.ID               =   "slidingDiv";
			mnu.ID                      =   "NavMen";
			mnu.Bind                    =   BindOption.BindOptionTop;
			mnu.UseTabNameInUrl         =   true;
			mnu.ShowImages              =   true;
			mnu.AutoBind                =   true;
			mnu.ExpandMode              =   Telerik.Web.UI.PanelBarExpandMode.SingleExpandedItem;
			mnu.EnableTheming           =   true;
			mnu.PersistStateInCookie    =   true;
			if (AutoHide)
			{
				mnu.OnClientMouseOver   =   "PreventTimeOut";
				mnu.OnClientMouseOut    =   "HideMenu";
			}
			SlidingDiv.Controls.Add(mnu);
			Controls.Add(SlidingDiv);

			ChildControlsCreated        =   true;
			if ( WebControlsTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( "[V]HeaderMenuButton CreateControlHierarchy END.",WebControlsTraceSwitch.Sw.Info);
		}
		
		private void PrepareControlHierarchy()
		{
			if ( WebControlsTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenuButton PrepareControlHierarchy BEG ChildControlsCreated: {0}", ChildControlsCreated),WebControlsTraceSwitch.Sw.Info);
			EnsureChildControls();

			if( !PortalSettings.IsUnderCRM )
			{
				if (ImageStyle.IsEmpty)
				{
					Img.Style.Add("float","left");
					Img.Style.Add("outline","0");
				}
				else Img.MergeStyle(ImageStyle);
				if (WebControlsTraceSwitch.Sw.TraceVerbose)
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenuButton PrepareControlHierarchy SlidingDivStyle.IsEmpty: {0}, SlidingDivStyle: {1}", SlidingDivStyle.IsEmpty,SlidingDivStyle), WebControlsTraceSwitch.Sw.Info);
				if (SlidingDivStyle.IsEmpty)
				{
					SlidingDiv.Style.Add(HtmlTextWriterStyle.Position, "absolute");
					SlidingDiv.Style.Add(HtmlTextWriterStyle.Display, "none");
					SlidingDiv.Style.Add(HtmlTextWriterStyle.Left, "50px");
					SlidingDiv.Style.Add(HtmlTextWriterStyle.Top, "0");
					SlidingDiv.Style.Add(HtmlTextWriterStyle.Width, "250px");
					SlidingDiv.Style.Add(HtmlTextWriterStyle.Height, "600px");
				}
				else
				{
					SlidingDiv.MergeStyle(SlidingDivStyle);
				}

				if ( !PanelBarStyle.IsEmpty )
					mnu.MergeStyle(PanelBarStyle);

				Visible                     =   true;
			}
			else
			{
				Visible                     =   false;
			}
			if ( WebControlsTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( "[V]HeaderMenuButton PrepareControlHierarchy END.",WebControlsTraceSwitch.Sw.Info);
		}

		#region ViewState 

		/// <summary>
		/// This member overrides Control.LoadViewState
		/// </summary>
		protected override void LoadViewState(object savedState) 
		{
			if ( PageTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( "[V]HeaderMenuButton LoadViewState BEG.",PageTraceSwitch.Sw.Info);
			// Customize state management to handle saving state of contained objects.
			if (savedState != null) 
			{
				object[] myState    =   (object[])savedState;

				if (myState[0] != null)
					base.LoadViewState(myState[0]);
				if (myState[1] != null)
					((IStateManager)_ImageStyle).LoadViewState(myState[1]);
				if (myState[2] != null)
					((IStateManager)_SlidingDivStyle).LoadViewState(myState[2]);
				if (myState[3] != null)
					((IStateManager)_PanelBarStyle).LoadViewState(myState[3]);
			}
			if ( PageTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( "[V]HeaderMenuButton LoadViewState END.",PageTraceSwitch.Sw.Info);
		}
		
		/// <summary>
		/// This member overrides Control.SaveViewState
		/// </summary>
		protected override object SaveViewState() 
		{
			if ( PageTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( "[V]HeaderMenuButton SaveViewState BEG.",PageTraceSwitch.Sw.Info);
			// Customized state management to handle saving state of contained objects  such as styles.
			object baseState                =   base.SaveViewState();
			object ImageStyleState          =   (_ImageStyle != null) ? ((IStateManager)_ImageStyle).SaveViewState() : null;
			object SlidingDivStyleState     =   (_SlidingDivStyle != null) ? ((IStateManager)_SlidingDivStyle).SaveViewState() : null;
			object PanelBarStyleState       =   (_PanelBarStyle != null) ? ((IStateManager)_PanelBarStyle).SaveViewState() : null;

			object[] myState                =   new object[4];
			myState[0]                      =   baseState;
			myState[1]                      =   ImageStyleState;
			myState[2]                      =   SlidingDivStyleState;
			myState[3]                      =   PanelBarStyleState;
			if ( PageTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( "[V]HeaderMenuButton SaveViewState END.",PageTraceSwitch.Sw.Info);
			return myState;
		}

		/// <summary>
		/// This member overrides Control.TrackViewState.
		/// </summary>
		protected override void TrackViewState() 
		{
			if ( PageTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( "[V]HeaderMenuButton TrackViewState BEG.",PageTraceSwitch.Sw.Info);
			// Customized state management to handle saving state of contained objects such as styles.
			base.TrackViewState();

			if (_ImageStyle!= null)
				((IStateManager)_ImageStyle).TrackViewState();
			if (_SlidingDivStyle!= null)
				((IStateManager)_SlidingDivStyle).TrackViewState();
			if (_PanelBarStyle != null)
				((IStateManager)_PanelBarStyle).TrackViewState();
		}

		#endregion ViewState 
		
		protected override void OnPreRender(EventArgs e)
		{
			if (WebControlsTraceSwitch.Sw.TraceVerbose)
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenuButton OnPreRender BEG IsPostBack: {0}, Visible: {1}", Page.IsPostBack,Visible), WebControlsTraceSwitch.Sw.Info);
			base.OnPreRender(e);
			EnsureChildControls();
			PrepareControlHierarchy();
			if ( !DesignMode & Visible && ((ADNPage)Page).HasAjaxManager)
			{
				StringBuilder sb =  new StringBuilder();
				sb.AppendFormat("panelDomElement = $get('{0}');\n", mnu.ClientID);
				sb.AppendFormat("slider = $get('{0}');\n", Img.ClientID);
				if (AutoHide)
					sb.AppendFormat("timerlength = {0};\n", HideTimeOut);
				//sb.AppendFormat("if (panelDomElement){{ SetUpAnimation('{0}', Telerik.Web.UI.SlideDirection.Right,panelDomElement);}}", Img.ClientID);
				sb.Append("if (panelDomElement){ SetUpAnimation();}\n");
				string scrpt    =   sb.ToString();
				if (WebControlsTraceSwitch.Sw.TraceVerbose)
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenuButton OnPreRender ResponseScripts.Add script: {0}", scrpt), WebControlsTraceSwitch.Sw.Info);
				((ADNPage)Page).AjaxManager.ResponseScripts.Add(scrpt);
				string gPath    =   Path.ToAbsolute(Config.PortalScriptsPath + "/SlideButton.js");
				((ADNPage)Page).RegisterADNClientScriptInclude(GetType(), "SlideButton", gPath);
			}
			if (WebControlsTraceSwitch.Sw.TraceVerbose)
				Trace2.WriteLine("[V]HeaderMenuButton OnPreRender END.", WebControlsTraceSwitch.Sw.Info);
		}
	}
}
